from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
import redis
from django.contrib.auth.mixins import LoginRequiredMixin
from pure_pagination import Paginator, PageNotAnInteger
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from apps.users.forms import *
from apps.users.models import *
from apps.operations.models import *
from apps.organizations.models import *
from WeiJi.settings import yp_apikey, REDIS_HOST, REDIS_PORT


# 登录类
class LoginView(View):
    def get(self, request, *args, **kwargs):
        next = request.GET.get("next", "")
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, 'login.html', {
                "next": next,
            })

    def post(self, request, *args, **kwargs):
        # 表单验证
        login_form = LoginForm(request.POST)
        # 如果表单验证通过
        if login_form.is_valid():
            user_name = login_form.cleaned_data["username"]
            password = login_form.cleaned_data["password"]
            user = authenticate(username=user_name, password=password)

            # 用户名不为空
            if user is not None:
                login(request, user)
                next = request.GET.get("next", "")
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect(reverse("index"))

            else:
                return render(request, "login.html", {"msg": "登录失败！用户名或密码错误", "login_form": login_form})
        else:
            return render(request, "login.html", {"login_form": login_form})


# 注册类
class RegisterView(View):
    def get(self, request, *args, **kwargs):
        user_name = ''
        return render(request, 'register.html', {
            "user_name": user_name,
        })

    def post(self, request, *args, **kwargs):
        register_post_form = RegisterPostForm(request.POST)
        if register_post_form.is_valid():
            # 获取用户名
            username = request.POST.get("username")
            # 获取邮箱
            email = register_post_form.cleaned_data["email"]
            # 验证邮箱是否已经注册
            users = UserProfile.objects.filter(email=email)
            if users:
                return render(request, "register.html", {
                    "msg": "注册失败！邮箱已被注册",
                    "email": email,
                    "user_name": username,
                })
            else:
                # 获取密码
                password = register_post_form.cleaned_data["password1"]
                confirm_password = register_post_form.cleaned_data["confirm_password"]

                if password != confirm_password:
                    return render(request, "register.html", {
                        "msg": "注册失败！两次密码输入不一致",
                        "email": email,
                        "user_name": username,
                    })

                else:
                    # 新建一个用户
                    user = UserProfile(username=username)
                    user.set_password(password)
                    user.email = email
                    user.save()
                    login(request, user)
                    return HttpResponseRedirect(reverse("index"))

        else:
            return render(request, "register.html", {"msg": "输入出错"})


# 退出登录类
class LogoutView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            logout(request)
            return HttpResponseRedirect(reverse("index"))


# 个人资料类
class UserInfoView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        nav_tab = request.GET.get("nav_tab", "")
        current_page = "info"
        return render(request, "usercenter-info.html", {
            "current_page": current_page,
            "nav_tab": nav_tab,
        })

    def post(self, request, *args, **kwargs):
        user_info_form = UserInfoForm(request.POST, instance=request.user)
        if user_info_form.is_valid():
            user_info_form.save()
            return JsonResponse({
                "status": "success",
            })
        else:
            return JsonResponse(user_info_form.errors)


# 修改密码类
class ChangePwdView(LoginRequiredMixin, View):
    login_url = "/login/"

    def post(self, request, *args, **kwargs):
        pwd_form = ChangePwdForm(request.POST)
        if pwd_form.is_valid():
            new_password1 = request.POST.get("new_password1", "")
            new_password = request.POST.get("new_password", "")
            user = request.user

            if new_password == new_password1:
                user.set_password(new_password)
                user.save()
                logout(request)
                return HttpResponseRedirect(reverse("login"))

            else:
                return render(request, "usercenter-info.html", {
                    "msg": "两次输入的密码不一致",
                    "nav_tab": "update_pwd",
                })

        else:
            return render(request, "usercenter-info.html", {
                "msg": "输入格式错误（长度至少要5位）",
                "nav_tab": "update_pwd",
            })


# 更新头像类
class UploadImageView(LoginRequiredMixin, View):
    login_url = "/login/"

    def post(self, request, *args, **kwargs):
        # 处理用户上传的头像
        image_form = UploadAvatarForm(request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()
            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse({
                "status": "fail"
            })


# 我收藏的课程类
class MyFavCourseView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        nav_tab = request.GET.get("nav_tab", "")
        current_page = "myfav_course"
        course_list = []
        fav_courses = UserFavorites.objects.filter(user=request.user, fav_type=1)
        for fav_course in fav_courses:
            try:
                course = Course.objects.get(id=fav_course.fav_id)
                course_list.append(course)
            except Course.DoesNotExist as e:
                pass
        return render(request, "usercenter-fav-course.html", {
            "course_list": course_list,
            "current_page": current_page,
            "nav_tab": nav_tab,
        })


# 我收藏的讲师类
class MyFavTeacherView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        nav_tab = request.GET.get("nav_tab", "")
        current_page = "myfav_teacher"
        teacher_list = []
        fav_teachers = UserFavorites.objects.filter(user=request.user, fav_type=3)
        for fav_teacher in fav_teachers:
            org = Teacher.objects.get(id=fav_teacher.fav_id)
            teacher_list.append(org)
        return render(request, "usercenter-fav-teacher.html", {
            "teacher_list": teacher_list,
            "current_page": current_page,
            "nav_tab": nav_tab,
        })


# 我收藏的机构类
class MyFavOrgView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        nav_tab = request.GET.get("nav_tab", "")
        current_page = "myfavorg"
        org_list = []
        fav_orgs = UserFavorites.objects.filter(user=request.user, fav_type=2)
        for fav_org in fav_orgs:
            org = CourseOrg.objects.get(id=fav_org.fav_id)
            org_list.append(org)
        return render(request, "usercenter-fav-org.html", {
            "org_list": org_list,
            "current_page": current_page,
            "nav_tab": nav_tab,
        })


# 我的消息类
class MyMessageView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        nav_tab = request.GET.get("nav_tab", "")
        messages = UserMessage.objects.filter(user=request.user)
        current_page = "message"
        for message in messages:
            message.has_read = True
            message.save()

        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(messages, per_page=1, request=request)
        messages = p.page(page)

        return render(request, "usercenter-message.html", {
            "messages": messages,
            "current_page": current_page,
            "nav_tab": nav_tab,
        })
